import javax.xml.stream.events.NotationDeclaration;

public class HashBuck {

    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node (int key,int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;

    public void push(int key,int val) {
        //要插入的数据
        Node node = new Node(key,val);

        //1.找到位置(根据键来确定位置）
        int index = key % array.length;

        //2.遍历数组
        Node cur = array[index];

        if (cur == null) {
            //头插法插入数据
            array[index] = node;
            usedSize++;
            return;
        }

        while(cur != null) {
            //判断是否存在->更新
            if (cur.val == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //遍历完还没找到-> 头插法 ??
        //头插.png
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if (doLoadFactor() > 0.75) {
            //处理了 重新哈希
            reSize();
        }
    }

    private void reSize() {
        Node[] newArray = new Node[array.length*2];
        //处理重新hash
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                int index = cur.key % newArray.length;
                //记录下来 之前的cur.next
                Node curNext = cur.next;
                //进行头插法，插入到新数组
                //头插2.png
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        // 把数据给到元数组 array
        array = newArray;
    }

    public int get(int key) {
        //1.找到位置
        int index = key % array.length;
        //2.遍历数组
        Node cur = array[index];
        while(cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

    private double doLoadFactor() {
        return usedSize * 1.0 / array.length;
    }

}
